package com.zgd.demo;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

	@Autowired
	private UserRepository userRepository;
	
	//查找全部
	@GetMapping(value="/user")
	public List<User> userList(){
		List<User> list = userRepository.findAll();
		return list;
	}
	
	//添加一个人
	@PostMapping(value="/user")
	public User userAdd(@RequestParam("username") String username,
						@RequestParam("userage") Integer userage,
						@RequestParam("useraddress") String useraddress,
						@RequestParam("money") Integer money){
		User user = new User();
		user.setUsername(username);
		user.setUserage(userage);
		user.setUseraddress(useraddress);
		user.setMoney(money);
		return userRepository.save(user);
	}
	
	/*根据id查找*/
	@GetMapping(value="/user/{id}")
	public User userFindById(@PathVariable Integer id){
		return userRepository.findOne(id);
	}
	
	/*更新根据id*/
	@PutMapping(value="/user/{id}")
	public User userUpdate(@PathVariable Integer id,
							@RequestParam("username") String username,
							@RequestParam("userage") Integer userage,
							@RequestParam("useraddress") String useraddress,
							@RequestParam("money") Integer money
							){
		User user = new User();
		user.setId(id);
		user.setUsername(username);
		user.setUserage(userage);
		user.setUseraddress(useraddress);
		user.setMoney(money);
		return userRepository.save(user);
	}
	
	/*删除根据id*/
	@DeleteMapping(value="/user/{id}")
	public void userDelete(@PathVariable Integer id){
		userRepository.delete(id);
	}
}
